package com.make.house.api.utils;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.make.house.api.common.CommonParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * Created by xujun on 2017/11/17.
 * 接口签名的公共类
 */
public class AppSignUtil {
    protected static Logger logger= LoggerFactory.getLogger(AppSignUtil.class);

    public static String generateAuthToken(String uid, String platform, String device_id, long login_time){
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("platform", platform);
            jsonObject.put("device_id", device_id);
            jsonObject.put("uid", uid);
            jsonObject.put("login_time", login_time);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //进行Base64加密
        return Base64.encode(jsonObject.toString().getBytes());
    }



    /**
     * 将HashMap中的参数生成签名（参数排序后连接起来md5）
     */
    public static String getTheAppSign(HashMap<String, String> table) {
        TreeMap<String, String> tree = new TreeMap<String, String>();
        if (table != null) {
            Set<Map.Entry<String, String>> enu = table.entrySet();
            for (Map.Entry<String, String> item : enu) {
                tree.put(item.getKey(), item.getValue());
            }
        }
        StringBuffer sb = new StringBuffer();
        Set<String> keys = tree.keySet();
        for (String key : keys) {
            sb.append(key).append(tree.get(key));
        }
        sb.append(CommonParams.APP_SECRET);
        logger.debug("getTheAppSign-->" + sb.toString());
        return MD5Util.getMD5(sb.toString().getBytes());
    }
}
